package com.csi.controller.user;

import com.alibaba.fastjson2.JSON;
import com.csi.domain.User;
import com.csi.pojo.Result;
import com.csi.service.UserService;
import com.csi.service.impl.UserServiceImpl;
import com.csi.utils.CreateQR;
import com.google.zxing.WriterException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

@WebServlet("/user/QRCodeFindController")
public class QRCodeController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        // 获取请求参数
        String userNumber = req.getParameter("userNumber");
        int userId = Integer.parseInt(req.getParameter("userId"));

        UserService userService = new UserServiceImpl();


        String path = "/QR/" + userNumber + "/";
        //新建一个文件夹 作为二维码生成的路径
        String realFilePath = req.getServletContext().getRealPath(path);
        //构建文件夹
        //文件夹路径
        //获取到要构建的文件夹路劲
        File f = new File(realFilePath);
        //判断文件目录是否存在，不存在就构建文件夹路径
        if (!f.exists()) { //不存在
            f.mkdirs();
        }
        //创建好用户编号的文件夹

        //生成的二维码存储路径
        String codePath = realFilePath + "/" + UUID.randomUUID().toString() + ".png";
        try {
            CreateQR.generateQRCode(userNumber, codePath);
            //生成了新的二维码
        } catch (WriterException e) {
            throw new RuntimeException(e);
        }

        //则之前存在路径
        String sub = "\\QR";
        int index = codePath.indexOf(sub);
        System.out.println(index);

        //截取到\\QR之后的路径
        codePath = codePath.substring(index);
        codePath = codePath.replaceAll("\\\\", "/");

        System.out.println(codePath);
        userService.uploadCodePath(codePath, userId);

        User user1 = userService.findById(userId);
        codePath = user1.getCodePath();

        Result result = new Result<>();
        result.setCode(200);
        result.setMsg("success");
        result.setDatas(codePath);

        out.print(JSON.toJSONString(result));

        out.flush();
        out.close();
    }
}
